package com.token;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;


@Component
public class JwtUtil {
/**
     *密码，绝对保密，写在配置文件中
     */


    private static String secretKey;
    private static long keeptime;

    @Value("${secretKey}")
    public void setSecretKey(String secretKey){
        JwtUtil.secretKey = secretKey;
    }
    @Value("${keeptime}")
    public void setSecretKey(long keeptime){
        JwtUtil.keeptime = keeptime;
    }
/**
     * 产生/更新令牌
     * @param username 用户名
     * @param issuer  签发者
     * @param subject 主体（内容)
     * @return
     */

    public static String generToken(String username, String issuer, String subject) {
        long ttlMillis = keeptime;
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        JwtBuilder builder = Jwts.builder().setId(username)
                .setIssuedAt(now);
        if (subject != null) {
            builder.setSubject(subject);
        }
        if (issuer != null) {
            builder.setIssuer(issuer);
        }
        builder.signWith(signatureAlgorithm, signingKey);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }


/**
     * 获取用户名
     * @param token
     * @return
     */

    public static String getUsername(String token) {

        Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))

                    .parseClaimsJws(token).getBody();
        return claims.getId();
    }


    public static String verifyToken(String token) {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
                    .parseClaimsJws(token).getBody();
            String username = claims.getId();
            String subject = claims.getSubject();
            String issuer = claims.getIssuer();
            return generToken(username,subject,issuer);
    }


}
